package com.cindata.api

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import groovy.json.JsonOutput
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import groovy.util.slurpersupport.GPathResult
import groovyx.net.http.ContentType
import groovyx.net.http.FromServer

//import groovyx.net.http.HTTPBuilder
import groovyx.net.http.HttpBuilder
import groovyx.net.http.Method
import groovyx.net.http.Method.*
import groovyx.net.http.ContentType.*
import groovyx.net.http.OkHttpBuilder
import groovyx.net.http.RESTClient
import okhttp3.OkHttpClient
import org.springframework.beans.factory.InitializingBean
import org.springframework.beans.factory.annotation.Value

import java.util.concurrent.TimeUnit

class MicronautService implements InitializingBean
{

    static scope = "singleton"
    OkHttpBuilder http

    @Value('${micronaut.address}')
    String micronautAddress
    @Value('${micronaut.batchEstate}')
    String batchEstate

    def batchInsert(Map data)
    {
        def result
        try
        {
            result = post(batchEstate, data)
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    @Override
    void afterPropertiesSet() throws Exception
    {
        http = OkHttpBuilder.configure {
            request.uri = micronautAddress
            client.clientCustomizer { OkHttpClient.Builder builder ->
                builder.connectTimeout(10, TimeUnit.SECONDS)
                builder.readTimeout(20, TimeUnit.SECONDS)
            }
        }
    }

    def post(String url, Map data)
    {
        try
        {
            http.post {
                request.uri.path = "${url}"
                request.contentType = ContentType.JSON
                if (data)
                {
                    request.body = data
                }
                log.info("--------------------->准备API请求，地址：${request.uri.path},key：${request.uri.query}")
                log.info("--------------------->准备API请求，参数：${JsonOutput.toJson(request.body).toString()}")
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println json
                    return json
                }
                response.failure { resp ->
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }
}
